package juc;

import java.util.concurrent.CountDownLatch;

/**
 * 闭锁:在完成某些运算时，只有其他线程运算全部完成，当前运算才继续执行
 *
 * @author liweimin
 * @date 2021/5/25 18:48
 * @since
 */
public class CountDownLatchTest {

    public static void main(String[] args) {
        final CountDownLatch countDownLatch = new CountDownLatch(10);//倒计时
        LatchDemo latchDemo = new LatchDemo(countDownLatch);
        long l = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            new Thread(latchDemo).start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("耗费时间为：" + (System.currentTimeMillis() - l));
    }

    private static class LatchDemo implements Runnable {

        private CountDownLatch latch;

        public LatchDemo(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public synchronized void run() {
            try {
                for (int i = 0; i < 40000; i++) {
                    if (i % 2 == 0) {
                        System.out.println(i);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }

        }
    }

}
